//封装GET请求

async function _login(){
  return new Promise((resolved, rejected) =>{
    wx.login({
      timeout: 5000,
      success: async info => {
        const App = getApp()
        await App.ports.api21({
          data: {
            appid: App.globalData.appid,
            code: info.code
          }
        }).then(res => {
          wx.setStorageSync('access', res.data.access);
          wx.setStorageSync('refresh', res.data.refresh);
          wx.setStorageSync('userId', res.data.id);
          if (res.data.active_role) {
            wx.setStorageSync('identity', res.data.active_role.title);
          }
          App.globalData.login = false;
          resolved(res)
        }).catch(res => {
          console.error(res.statusCode, res.data)
          rejected(res)
        })
      },
      complete: res => {
      },
      fail: res => {
      }
    })
  })
}

async function _post_refresh({
  method,
  url,
  data,
  header,
  responseType
}) {
  return new Promise((resolved, rejected) => {
    wx.request({
      url: getApp().globalData.url2 + '/api/public/v1/refresh',
      method: 'POST',
      header: {
        "Authorization": `Bearer ${wx.getStorageSync('refresh')}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.setStorageSync('access', res.data.access)
          wx.setStorageSync('refresh', res.data.refresh)
          resolved(res)
        } else {
          //  getApp().login({
          //   method,
          //   url,
          //   data,
          //   header,
          //   responseType
          // });
          wx.setStorageSync('access', '');
          wx.setStorageSync('refresh', '');
          console.error("再走登录流程")
          _login().then(res => {
            resolved(res)
          })
        }
      }
    })
  })
}
async function _getToken({
  method,
  url,
  data,
  header,
  responseType
}) {
  return new Promise((resolved, rejected) => {
    wx.request({
      url: url,
      data: data,
      header: {
        "Authorization": `Bearer ${wx.getStorageSync('access')}`,
        ...header
      },
      method: method,
      responseType: responseType || "text",
      success: async function (res) {
        // console.log("------------------------------------------->>>>>", res)
        if (res.data.timeStamp && res.data.package) {
          resolved(res.data);
          return;
        }
        if (res.data.code == 200) {
          resolved(res.data)
        }else if (res.data.code == 401) {
          // 跳转到登录页面 redirectTo  navigateTo  如果没登录不跳了 没意义了 自动登录就可以了
          // wx.redirectTo({
          //   url: '/pages/login/login'
          // })

          await _login().then(res => {
            // 重新调用一次接口
            _getToken({method, url, data, header, responseType }).then(resnn => {
              resolved(resnn)
            })
          })

        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'error',
            duration:2000
          })
          rejected(res.data)
        }


        // if (res.statusCode >= 200 & res.statusCode < 400) {
        //   resolved(res.data)
        // } else if (res.statusCode == 401) {
        //   let token = await _post_refresh({
        //     method,
        //     url,
        //     data,
        //     header,
        //     responseType
        //   }).then(res => res.data)
        //   wx.request({
        //     url: url,
        //     data: data,
        //     method: method,
        //     header: {
        //       "Authorization": `Bearer ${wx.getStorageSync('access')}`,
        //       ...header
        //     },
        //     success: function (res) {
        //       res.statusCode >= 200 && res.statusCode < 300 ? resolved(res) : rejected(res)
        //     }
        //   })
        // }else {
        //   console.error("发生错误！")
        // }
      },
      complete: function (res) {
        if(res.errMsg != "request:ok"){
          console.debug('complete', url, res)
        }
        if(res.errMsg == "request:ok" && res.statusCode == 403 && res.data.detail != 'Forbidden'){
          console.log(res)
          wx.showToast({
            title: res.data.detail,
            icon:'none',
            duration:1000
          })
          return
        }
      }
    })
  })

}
//封装POST请求
function _post({
  url,
  data,
  header,
  responseType
}) {
  return _getToken({
    method: "POST",
    url,
    data,
    header,
    responseType
  })
}
//封装的_get方法
function _get({
  url,
  data,
  header
}) {
  return _getToken({
    method: 'GET',
    url: url,
    data
  })
}

function _delete({
  url,
  data,
  header
}) {
  return _getToken({
    method: 'DELETE',
    url,
    data
  })
}

function _patch({
  url,
  data,
  header
}) {
  return _getToken({
    method: 'POST',
    header:{
      'X-HTTP-Method-Override': 'PATCH'
    },
    url,
    data
  })
}


function _put({
  url,
  data,
  header
}) {
  return _getToken({
    method: 'PUT',
    url,
    data
  })
}

function _uploadFile({
  url,
  filePath,
  name,
  formData
}) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      formData: formData,
      header: {
        "Authorization": `Bearer ${wx.getStorageSync('access')}`,
      },
      success: (res) => {
        // wx.hideLoading();
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // uploadFile的res.data是字符串，需要手动解析
          try {
            const parsedData = JSON.parse(res.data);
            resolve(parsedData);
          } catch (e) {
            console.error("JSON parse error:", e, res.data);
            reject({ errMsg: "JSON parse error", data: res.data });
          }
        } else if (res.statusCode === 401) {
          // token过期，可以加入刷新token的逻辑
          console.error("Token expired, please re-login.");
          _login().then(() => {
            // 重新上传
            _uploadFile({ url, filePath, name, formData }).then(resolve).catch(reject);
          }).catch(reject);
        } else {
          console.error('uploadFile fail', res);
          reject(res);
        }
      },
      fail: (err) => {
        // wx.hideLoading();
        console.error('uploadFile fail', err);
        reject(err);
      }
    });
  });
}

function _post_stream({ url, data, header, onChunkReceivedCallback, onError, onComplete }) {
  console.log('发起流式请求:', { url, data });
  
  const requestTask = wx.request({
    url: url,
    data: data,
    method: 'POST',
    responseType: 'arraybuffer',
    enableChunked: true,
    timeout: 12000000,
    
    success: (res) => {
      console.log('流式请求成功响应:', res);
      if (res.statusCode !== 200) {
        console.error('流式请求状态码异常:', res.statusCode, res);
        if (onError) {
          onError(res);
        }
      }
    },
    fail: (error) => {
      console.error('流式请求失败:', error);
      if (onError) {
        onError(error);
      }
    },
    complete: (res) => {
      console.log('流式请求完成:', res);
      if (onComplete) {
        onComplete(res);
      }
    }
  });

  if (requestTask?.onChunkReceived) {
    requestTask.onChunkReceived(onChunkReceivedCallback);
  } 

  return requestTask;
}

//导出封装
export default {
  _post,
  _get,
  _delete,
  _put,
  _patch,
  _getToken,
  _post_stream,
  _uploadFile
}